#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

namespace dict_ns
{
    const std::string default_path = "./Dict.txt";
    const std::string sep = ": ";

    class Dict
    {

    private:
        bool LoadDict()
        {
            //打开_path下的文件
            std::ifstream ifs(_path);
            if (!ifs.is_open())
            {
                LOG(ERROR, "open %s failed", _path.c_str());

                return false;
            }

             //一行一行读取文件进line
            std::string line;
            while (std::getline(ifs, line))
            {

                if (line.empty())
                    continue;

                //查找分隔符
                auto pos = line.find(sep);
                if (pos == std::string::npos)
                    continue;
                
                std::string work = line.substr(0, pos);
                if (work.empty())
                    continue;

                std::string chinese = line.substr(pos + sep.size());
                if (chinese.empty())
                    continue;

                    _dict.insert(std::make_pair(work, chinese));    

                //LOG(DEBUG, "load info:%s %s\n", work.c_str(), chinese.c_str());

            }

            ifs.close();
            LOG(DEBUG, "load %s success", _path.c_str());

            return true;
        }

    public:
        Dict(const std::string &path = default_path)
            : _path(path)
        {
            LoadDict();
        }

        std::string Translate(const std::string& word,bool &issave)
        {
            issave=true;

            auto iter = _dict.find(word);
            if(iter==_dict.end())
            {
                issave=false;
                return "not found";
            }

            return iter->second;
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _path;
    };

}
